﻿using MesBSW.BLL.Mes;
using MesBSW.BLL.Role;
using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using MesBSW.DAL.RoleDB;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesBSW.View.Mes.Scan
{
    public partial class OtherSiteScanFrm : UIPage
    {
        #region "内部变量"
        private BaseUserModel _curr_user = null;
        private StatusInfo _curr_status = null;
        private SiteInfo _curr_site = null;

        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<StatusInfo> _prod_status_list = new List<StatusInfo>();
        private List<StatusInfo> _err_status_list = new List<StatusInfo>();
        private ProdProcScanControler _ctrl = new ProdProcScanControler();
        private UserInfoControler _user_ctrl = new UserInfoControler();
        #endregion

        public OtherSiteScanFrm()
        {
            InitializeComponent();
        }

        #region "控件事件"
        /// <summary>
        /// 界面读取时，预设用户、站点和工单状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OtherSiteScanFrm_Load(object sender, EventArgs e)
        {
            //查询系统中所有的站点和工单状态
            this._site_list = this._ctrl.SearchAllSiteInfo();
            this._prod_status_list = this._ctrl.SearchStatusInfoByTypeName("工单状态");
            this._err_status_list = this._ctrl.SearchStatusInfoByTypeName("异常状态");

            //将系统登陆用户预成界面的当前用户
            this._curr_user = MainFrm.LoginUser;

            //预设界面的站点，并通过站点预设界面的工单状态
            if (this._site_list != null && this._site_list.Count > 0)
            {
                this._curr_site = this._site_list[0];
                this._curr_status = this.SetCurrStatusForSiteInfo(this._curr_site);
            }

            //如果站点没有默认工单状态，则从所有状态中选一个当成界面的当前状态
            if (this._curr_status == null && this._prod_status_list != null && this._prod_status_list.Count > 0)
            {
                this._curr_status = this._prod_status_list[0];
            }

            this.InitStatusStripInfo(this._curr_user, this._curr_status, this._curr_site);
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 设定界面下面的提示栏信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="status"></param>
        /// <param name="site"></param>
        private void InitStatusStripInfo(BaseUserModel user, StatusInfo status, SiteInfo site)
        {
            string tmpStr = "";
            if (user != null)
            {
                tmpStr = tmpStr + $"当前用户：{user.user_name}({user.real_name})     ";
            }
            else
            {
                tmpStr = tmpStr + "当前用户：" + "        ";
            }

            if (site != null)
            {
                tmpStr = tmpStr + "当前站点：" + site.SiteName + "        ";
            }
            else
            {
                tmpStr = tmpStr + "当前站点：" + "        ";
            }
            if (status != null)
            {
                tmpStr = tmpStr + "当前状态：" + status.StatusValue + "        ";
            }
            else
            {
                tmpStr = tmpStr + "当前状态：" + "        ";
            }
            this.toolStripStatusLabel1.Text = tmpStr;
        }


        /// <summary>
        /// 通过站点取得站点默认工单状态的信息
        /// </summary>
        private StatusInfo SetCurrStatusForSiteInfo(SiteInfo site)
        {
            StatusInfo resStatus = null;
            if (site != null && (site.DefStatus ?? 0) > 0)
            {
                if (this._prod_status_list != null && this._prod_status_list.Count > 0)
                {
                    var query = this._prod_status_list.Where(s => s.ID == (site.DefStatus ?? 0));
                    if (query != null & query.Count() > 0)
                    {
                        resStatus = query.First<StatusInfo>();
                    }
                }
            }
            return resStatus;
        }

        /// <summary>
        /// 通过扫码方式更改界面的当前站点
        /// </summary>
        /// <param name="scan"></param>
        /// <returns></returns>
        private SiteInfo SearchSiteInfoForScan(string scan)
        {
            SiteInfo resSite = null;
            if (this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(s => s.SiteCode == scan.Trim());
                if (query != null && query.Count() > 0)
                {
                    resSite = query.First<SiteInfo>();
                    StatusInfo tmpStatus = this.SetCurrStatusForSiteInfo(resSite);
                    if (tmpStatus != null && tmpStatus.ID > 0)
                    {
                        this._curr_status = tmpStatus;
                    }
                }
            }
            return resSite;
        }

        /// <summary>
        /// 通过扫码方式更改界面的当前工单状态
        /// </summary>
        /// <param name="scan"></param>
        /// <returns></returns>
        private StatusInfo SearchStatusInfoForScan(string scan)
        {
            StatusInfo resStatus = null;
            if (this._prod_status_list != null && this._prod_status_list.Count > 0)
            {
                var query = this._prod_status_list.Where(s => s.StatusCode == scan.Trim());
                if (query != null && query.Count() > 0)
                {
                    resStatus = query.First<StatusInfo>();
                }
            }

            if (resStatus == null)
            {
                if (this._err_status_list != null && this._err_status_list.Count > 0)
                {
                    var query = this._err_status_list.Where(s => s.StatusCode == scan.Trim());
                    if (query != null && query.Count() > 0)
                    {
                        resStatus = query.First<StatusInfo>();
                    }
                }
            }

            return resStatus;
        }

        /// <summary>
        /// 通过扫码方式更改界面的当前员工状态
        /// </summary>
        /// <param name="scan"></param>
        /// <returns></returns>
        private BaseUserModel SearchUserForScan(string scan)
        {
            BaseUserModel resUser = null;
            List<BaseUserModel> userList = this._user_ctrl.SearchUserForMuneClassName("Gl_mes.View.Mes.OtherSiteScanFrm");
            if (userList != null && userList.Count > 0)
            {
                var query = userList.Where(u => u.user_name == scan.Trim());
                if (query != null && query.Count() > 0)
                {
                    resUser = query.First<BaseUserModel>();
                }
            }
            return resUser;
        }

        /// <summary>
        /// 播放一段音频
        /// </summary>
        /// <param name="fileName"></param>
        private void PlayWav(string fileName)
        {
            if (System.IO.File.Exists(fileName))
            {
                SoundPlayer player = new SoundPlayer(fileName);
                player.Play();
            }
            else
            {
                UIMessageTip.ShowWarning("没找到音频文件，无法播放！" + "\r\n" + fileName);
            }
        }

        /// <summary>
        /// 检查资料是否合法
        /// </summary>
        /// <param name="target"></param>
        /// <param name="user"></param>
        /// <param name="site"></param>
        /// <param name="status"></param>
        /// <param name="scanQty">扫码的数量</param>
        /// <returns></returns>
        private string CheckData(TargetProdProcessDTO target, BaseUserModel user, SiteInfo site, StatusInfo status, decimal scanQty)
        {
            string errStr = "";
            if (user == null || user.id <= 0)
            {
                errStr = "当前用户为空，中止扫码！";
            }
            else if (site == null || site.ID <= 0)
            {
                errStr = "当前站点为空，中止扫码！";
            }
            else if (status == null || status.ID <= 0)
            {
                errStr = "当前工单状态为空，中止扫码！";
            }
            else if (status != null && (status.StatusValue.Equals("暂停") || status.StatusValue.Equals("取消暂停")))
            {
                errStr = "该界面不处理工单的暂停与取消暂停！";
            }
            else if (target.SiteGroup == null || target.SiteGroup.SiteInfoList == null || target.SiteGroup.SiteInfoList.Count <= 0)
            {
                errStr = "工单号：" + target.ProdNumber + "没与站点组绑定，或其站点组没与站点绑定！";
            }
            else 
            {
                bool isOK = true;
                SiteInfo lastSite = null;
                if (isOK)
                {
                    var query = target.SiteGroup.SiteInfoList.Where(q => q.SiteInfo.ID == site.ID);
                    if (query != null && query.Count() > 0)
                    {
                        if (query.First().Sort != 1)
                        {
                            var lastQuery = target.SiteGroup.SiteInfoList.Where(q => q.Sort == query.First().Sort - 1);
                            if (lastQuery != null && lastQuery.Count() > 0)
                            {
                                lastSite = lastQuery.First().SiteInfo;
                            }
                        }

                        if (query.First().SiteInfo.IsDel == 1)
                        {
                            errStr = $"站点：{site.SiteName}已经失效，不能扫码！";
                            isOK = false;
                        }
                    }
                    else
                    {
                        errStr = $"该工单对应的流程不包括站点：{site.SiteName}";
                        isOK = false ;
                    }
                }


                if (isOK)
                {
                    decimal clearQty = this._ctrl.GetProdScanQtyForSite(target.ProdNumber, site.ID);
                    decimal lastQty = 0;
                    if (lastSite != null && lastSite.ID > 0)
                    {
                        lastQty = this._ctrl.GetProdScanQtyForSite(target.ProdNumber, lastSite.ID);
                        if (lastQty == 0)
                        {
                            errStr = $"上一站点：{lastSite.SiteName}尚未开始扫码！";
                            isOK = false;
                        }
                        else if (scanQty > lastQty - clearQty)
                        {
                            errStr = $"本站扫码数量{scanQty} > 上站已扫{lastQty} - 本站已扫{clearQty}";
                            isOK = false;
                        }
                    }
                    else
                    {
                        lastQty = target.ProdQty ?? 0;
                        if (scanQty > lastQty - clearQty)
                        {
                            errStr = $"本站扫码数量{scanQty} > 上站已扫{lastQty} - 本站已扫{clearQty}";
                            isOK = false;
                        }
                    }
                }


                

                //判断工单是否有异常，是否能扫码
                //if (isOK == true)
                //{
                //    var errQuery = this._err_status_list.Where(s => s.ID == target.ErrStatusID);
                //    if (errQuery != null && errQuery.Count() > 0)
                //    {
                //        StatusInfo tmpStatus = errQuery.First();
                //        if (currSite is null)
                //        {
                //            errStr = "工单：" + target.ProdNumber + "无法确定工单当前所在位置，不能扫码！";
                //        }
                //        else if (tmpStatus.StatusValue.Equals("暂停"))
                //        {
                //            errStr = "工单：" + target.ProdNumber + "状态为暂停，不能扫码！";
                //        }
                //        else if ((tmpStatus.DispType ?? 0) != 0)
                //        {
                //            if (tmpStatus.DispType == 1 && maxIndex < tmpSort)
                //            {
                //                errStr = "工单严重异常，不能通过大站点的最后一站！";
                //            }
                //            else if (tmpStatus.DispType == 2 && site.ID == endSite2.ID)
                //            {
                //                errStr = "工单普通异常，必需在入库前处理！";
                //            }
                //        }
                //    }
                //}
            }
            return errStr;
        }
        #endregion

        private void txtScan_KeyPress(object sender, KeyPressEventArgs e)
        {
            //List<int> deptIds = bs.SelectUserDept(_curr_user.id);

            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                //判断是否扫码成功
                Boolean isSucc = false;

                //取出二维码，并将TextBox清空，方便下次扫码
                string tmpStr = this.txtScan.Text.Trim();
                this.txtScan.Text = "";


                if (isSucc == false)
                {
                    //检查所扫的二维码是否用户二维码，如果是，更改界面当前的用户信息，并标记扫码成功
                    BaseUserModel tmpUser = this.SearchUserForScan(tmpStr);
                    if (tmpUser != null && tmpUser.id > 0)
                    {
                        //deptIds = bs.SelectUserDept(tmpUser.id);
                        //用户输入工号时，判断工号是否已经被注销，注销的帐号不预扫码，2024-05-06，THOR
                        if (tmpUser.is_del.HasValue && ((bool)tmpUser.is_del) == true)
                        {
                            UIMessageBox.ShowError("用户：" + tmpUser.real_name + "帐号已经被注销，不能使用！");
                        }
                        else
                        {
                            this._curr_user = tmpUser;
                            this.InitStatusStripInfo(this._curr_user, this._curr_status, this._curr_site);
                            isSucc = true;
                        }
                    } 
                }

                if (isSucc == false)
                {
                    //检查所扫的二维码是否站点二维码，如果是，更改界面当前的站点信息，并标记扫码成功
                    SiteInfo tmpSite = this.SearchSiteInfoForScan(tmpStr);
                    //if (tmpSite != null)
                    //{
                    //    if (!deptIds.Contains(tmpSite.deptId))
                    //    {
                    //        UIMessageBox.ShowWarning("没有权限操作当前站点！");
                    //        return;
                    //    }
                    //}
                    if (tmpSite != null && tmpSite.ID > 0)
                    {
                        this._curr_site = tmpSite;
                        this.InitStatusStripInfo(this._curr_user, this._curr_status, this._curr_site);
                        isSucc = true;
                    }
                }

                if (isSucc == false)
                {
                    //检查所扫的二维码是否工单二维码，如果是，更改工单相关信息，并标记扫码成功
                    TargetProdProcessDTO tmpTarget = this._ctrl.SearchTargetForScan(tmpStr);
                    //if (tmpTarget != null)
                    //{
                    //    if (!deptIds.Contains(tmpTarget.DeptId))
                    //    {
                    //        UIMessageBox.ShowWarning("没有权限操作当前工单！");
                    //        return;
                    //    }
                    //}
                    if (tmpTarget != null && tmpTarget.ID > 0)
                    {
                        isSucc = true;
                        if (this._curr_status != null)
                        {
                            var prodQuery = this._prod_status_list.Where(s => s.ID == this._curr_status.ID);
                            var errQuery = this._err_status_list.Where(s => s.ID == this._curr_status.ID);
                            if (prodQuery != null && prodQuery.Count() > 0)
                            {
                                string errStr = this.CheckData(tmpTarget, this._curr_user, this._curr_site, this._curr_status, tmpTarget.ProdQty ?? 0);
                                if (errStr != null && errStr.Trim().Length > 0)
                                {
                                    UIMessageBox.ShowError(errStr);
                                    //SearchSiteGroupForProdDia tmpDia = new SearchSiteGroupForProdDia(errStr, tmpTarget.ProdNumber);
                                    //tmpDia.ShowDialog();
                                }
                                else
                                {
                                    try
                                    {
                                        this._ctrl.SaveProdProcessScan(tmpTarget, this._curr_user, this._curr_site, this._curr_status, tmpTarget.ProdQty ?? 0);
                                        UIMessageTip.ShowOk("扫码成功！");
                                        this.dgvScanDetail.DataSource = this.SearchScanRecordForProdNo(tmpTarget.ProdNumber);
                                    }
                                    catch (Exception ex)
                                    {
                                        UIMessageBox.ShowError("扫码失败！" + "\r\n" + ex.Message);
                                    }
                                }
                            }
                        }
                        else
                        {
                            UIMessageBox.ShowError("当前工单状态为空，中止扫码！");
                        }

                    }
                }

                if (isSucc == false)
                {
                    //最后如果扫码标记仍为false，报错
                    UIMessageBox.ShowWarning("无法识别二维码！");
                }
            }
        }

        private DataTable SearchScanRecordForProdNo(string prodNo)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("id");
            resDt.Columns.Add("prod_id");
            resDt.Columns.Add("prod_number");
            resDt.Columns.Add("site_id");
            resDt.Columns.Add("site_name");
            resDt.Columns.Add("status_id");
            resDt.Columns.Add("status_name");
            resDt.Columns.Add("scan_qty");
            resDt.Columns.Add("scan_user");
            resDt.Columns.Add("scan_date");

            List<ProdProcScan> scanList = this._ctrl.SearchScanForProdNumber(prodNo);
            if (scanList != null && scanList.Count() > 0)
            {
                scanList = scanList.OrderByDescending(s => s.ScanDate).ToList();
                foreach (ProdProcScan scan in scanList)
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["id"] = scan.ID;
                    addRow["prod_id"] = scan.ProdProcID;
                    addRow["prod_number"] = scan.ProdNumber;
                    addRow["site_id"] = scan.SiteInfoID;
                    addRow["site_name"] = scan.SiteName;
                    addRow["status_id"] = scan.StatusInfoID;
                    addRow["status_name"] = scan.StatusName;
                    addRow["scan_qty"] = scan.ScanQty;
                    addRow["scan_user"] = scan.ScanUser;
                    addRow["scan_date"] = scan.ScanDate;
                    resDt.Rows.Add(addRow);
                }
            }

            return resDt;
        }

    }
}
